package com.create;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Calendar;
import java.util.Hashtable;
import com.barcode.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.rsa.RsaHelper;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class createqr extends Activity{

	private static final int IMAGE_CODE = 0;
	private final String IMAGE_TYPE = "image/*";
	private EditText qrStrEditText;

	private ImageView qrImgImageView;
	private Button btnsave;
	protected Bitmap qrCodeBitmap,mBitmap;
	private Bitmap bitmap;
	private static final int IMAGE_HALFWIDTH = 20;
	int[] pixels = new int[2 * IMAGE_HALFWIDTH * 2 * IMAGE_HALFWIDTH];
	String contentString ;
	String encodingString;
	String strpublickey =
			"<RSAKeyValue><Modulus>6CdsXgYOyya/yQHTO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5LwPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sxPAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sPw9YRXiac=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

		String strprivatekey =
			"<RSAKeyValue><Modulus>6CdsXgYOyya/yQHTO96dB3gEurM2UQDDVGrZoe6RcAVTxAqDDf5LwPycZwtNOx3Cfy44/D5Mj86koPew5soFIz9sxPAHRF5hcqJoG+q+UfUYTHYCsMH2cnqGVtnQiE/PMRMmY0RwEfMIo+TDpq3QyO03MaEsDGf13sPw9YRXiac=</Modulus><Exponent>AQAB</Exponent><P>/aoce2r6tonjzt1IQI6FM4ysR40j/gKvt4dL411pUop1Zg61KvCm990M4uN6K8R/DUvAQdrRdVgzvvAxXD7ESw==</P><Q>6kqclrEunX/fmOleVTxG4oEpXY4IJumXkLpylNR3vhlXf6ZF9obEpGlq0N7sX2HBxa7T2a0WznOAb0si8FuelQ==</Q><DP>3XEvxB40GD5v/Rr4BENmzQW1MBFqpki6FUGrYiUd2My+iAW26nGDkUYMBdYHxUWYlIbYo6Tezc3d/oW40YqJ2Q==</DP><DQ>LK0XmQCmY/ArYgw2Kci5t51rluRrl4f5l+aFzO2K+9v3PGcndjAStUtIzBWGO1X3zktdKGgCLlIGDrLkMbM21Q==</DQ><InverseQ>GqC4Wwsk2fdvJ9dmgYlej8mTDBWg0Wm6aqb5kjncWK6WUa6CfD+XxfewIIq26+4Etm2A8IAtRdwPl4aPjSfWdA==</InverseQ><D>a1qfsDMY8DSxB2DCr7LX5rZHaZaqDXdO3GC01z8dHjI4dDVwOS5ZFZs7MCN3yViPsoRLccnVWcLzOkSQF4lgKfTq3IH40H5N4gg41as9GbD0g9FC3n5IT4VlVxn9ZdW+WQryoHdbiIAiNpFKxL/DIEERur4sE1Jt9VdZsH24CJE=</D></RSAKeyValue>";

		PublicKey publicKey = RsaHelper.decodePublicKeyFromXml(strpublickey);
		PrivateKey privateKey = RsaHelper.decodePrivateKeyFromXml(strprivatekey);

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.macreate);       
 
			qrStrEditText = (EditText) this.findViewById(R.id.et_qr_string);

			qrImgImageView = (ImageView) this.findViewById(R.id.iv_qr_image);
			btnsave=(Button)this.findViewById(R.id.btn_save);
    
			Button btncreate=(Button)this.findViewById(R.id.btn_create);		

				
			btnsave.setOnClickListener(new OnClickListener() {	
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Calendar cal = Calendar.getInstance();
					int y = cal.get(cal.YEAR);
					int m = cal.get(cal.MONTH) + 1;
					int d = cal.get(cal.DAY_OF_MONTH);
					int h = cal.get(cal.HOUR_OF_DAY);
					int mm = cal.get(cal.MINUTE);
					int s = cal.get(cal.SECOND);
					String name = String.format("%04d-%02d-%02d %02d_%02d_%02d.png", y,
						m, d, h, mm, s);
					try {
						saveBitmap(name, bitmap);
					} catch (Exception e) {
					e.printStackTrace();
					
				}
				Toast.makeText(createqr.this, "保存成功！" + name, 1).show();
				
			
			}
			
			
			private  void saveBitmap(String bitName, Bitmap mBitmap) throws Exception {
				File dir = new File(Environment.getExternalStorageDirectory()
						+ "/myImage/");
				if (!dir.exists()) {
					dir.mkdir();
				}
				File f = new File(dir.getAbsolutePath() + "/" + bitName);
				f.createNewFile();
				FileOutputStream fOut = null;
				fOut = new FileOutputStream(f);
				mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
				fOut.flush();
			}
			
		});
        btncreate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					contentString = qrStrEditText.getText().toString();
					if (!contentString.equals("")) {
						//根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小		
						int width = 600, height = 600;				// 根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（600

						QRCodeWriter writer = new QRCodeWriter();
						BitMatrix martix = writer.encode(contentString,
								BarcodeFormat.QR_CODE, width, height);
						System.out.println("w:" + martix.width + "h:"
									+ martix.height);
					
						Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
						hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
						BitMatrix bitMatrix = new QRCodeWriter().encode(contentString, 
														BarcodeFormat.QR_CODE, width,
														height, hints);
						int[] pixels = new int[width * height];
						for (int y = 0; y < height; y++) {
							for (int x = 0; x < width; x++) {
								if (bitMatrix.get(x, y)) {
									pixels[y * width + x] = 0xff000000;
								} else {
									pixels[y * width + x] = 0xffffffff;
								}

							}
						}

						bitmap = Bitmap.createBitmap(width, height,
								Bitmap.Config.ARGB_8888);

						bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

						
						qrImgImageView.setImageBitmap(bitmap);
						btnsave.setEnabled(true);
						}else {
							Toast.makeText(createqr.this, "Text can not be empty", Toast.LENGTH_SHORT).show();
						return;
					}
					
				} catch (WriterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

        } );
        Button btn_add_img=(Button)findViewById(R.id.btn_add_img);
        btn_add_img.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						String contentString = qrStrEditText.getText()
								.toString();
						if (contentString != null && !contentString.equals("")) {
							Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
							getAlbum.setType(IMAGE_TYPE);
							startActivityForResult(getAlbum, IMAGE_CODE);
						} else {
							Toast.makeText(getApplication(), "未填写信息",
									Toast.LENGTH_LONG).show();
						}
					}
				});
		}
    public void saveJpeg(Bitmap bm) {

		long dataTake = System.currentTimeMillis();
		String jpegName = initSavePath() + dataTake + ".jpg";
		try {
			FileOutputStream fout = new FileOutputStream(jpegName);
			BufferedOutputStream bos = new BufferedOutputStream(fout);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}
	}

	public String initSavePath() {
		File dateDir = Environment.getExternalStorageDirectory();
		String path = dateDir.getAbsolutePath() + "/myImage/";
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdir();
		}
		return path;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 处理扫描结果（在界面上显示）
		if (resultCode == RESULT_OK) {
			

			if (requestCode == IMAGE_CODE) {
				try {
					ContentResolver resolver = getContentResolver();
					Uri originalUri = data.getData();

					mBitmap = MediaStore.Images.Media.getBitmap(resolver,
							originalUri);
					Matrix m = new Matrix();
					float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth();
					float sy = (float) 2 * IMAGE_HALFWIDTH
							/ mBitmap.getHeight();
					m.setScale(sx, sy);
					mBitmap = Bitmap.createBitmap(mBitmap, 0, 0,
							mBitmap.getWidth(), mBitmap.getHeight(), m, false);
					String contentString = qrStrEditText.getText().toString();
					mBitmap = creatBitmap(new String(contentString.getBytes(),
							"utf-8"));
					qrImgImageView.setImageBitmap(mBitmap);
					saveJpeg(mBitmap);	//  带图片 的二维码
				} catch (Exception e) {

					Log.e("TAG-->Error", e.toString());

				}
			}
		}
	}
//jia ru picture
	public Bitmap creatBitmap(String str) throws WriterException {

		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		//hints.put(EncodeHintType.MARGIN, 1);

		BitMatrix matrix = new MultiFormatWriter().encode(str,
				BarcodeFormat.QR_CODE, 300, 300, hints);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int halfW = width / 2;
		int halfH = height / 2;
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
						&& y > halfH - IMAGE_HALFWIDTH
						&& y < halfH + IMAGE_HALFWIDTH) {
					pixels[y * width + x] = mBitmap.getPixel(x - halfW
							+ IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
				} else {
					if (matrix.get(x, y)) {
						pixels[y * width + x] = 0xff000000;
					} else {
						pixels[y * width + x] = 0xffffffff;
					}
				}
			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height,
								Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

		return bitmap;
	}
}